import React, { Component } from "react";
import './AudioPlay.scss'
import { Button, Slider, Avatar, Drawer } from 'antd';
import emitter from '../../event';
import {GetSongUrls, GetAudioLyric, GetAudioDetail} from "../../api/buttonAudio/buttonAudio";
import { connect } from "react-redux";
import { SetLyricsShow, SethistroyList, SethistoryActive, SetHistoryListActiveItem, SetPlayAudioType, SetLastActiveAudio, SetLyricsList, SetAudioLyricsLine, SetIsAudioPlay } from "../../store/action";
import Lyric from "../../util/Lyric";
import MusicHistoryList from "../MusichistroyList/histroylist";
import classnames from 'classnames';
import { getToken } from "../../assets/cookies";
import ScreenLyricsPage from "../ScreenLyrics/ScreenLyrics";

const mapStateToProps = (state) => {
    return {
        state,
    };
}

let lyricInstance;

const mapDispatchToProps = (dispatch) => {
    return {
        setlyrics: (form) => dispatch(SetLyricsShow(form)),
        sethistory: (list) => dispatch(SethistroyList(list)),
        sethistoryactive: (id) => dispatch(SethistoryActive(id)),
        setHistoryActiveItem: (info) => dispatch(SetHistoryListActiveItem(info)),
        setPlayType: (type) => dispatch(SetPlayAudioType(type)),
        setLastAudioActive: (list) => dispatch(SetLastActiveAudio(list)),
        setLyricsList: (list) => dispatch(SetLyricsList(list)),
        setLineLyrics: (line) => dispatch(SetAudioLyricsLine(line)),
        setIsAudioPlay: (bool) => dispatch(SetIsAudioPlay(bool)),
    }
}

class AudioPlay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            src: '',
            id: '',
            rateList: [1.0, 1.25, 1.5, 2.0],
            playRate: 1.0,
            isPlay: false,
            isMuted: false,
            volume: 100,
            allTime: 0,
            currentTime: 0,
            isSend:false,
            MusicInfo: null,
            isopenlyrics: false,
            showVolumeChange: false,
            Drawervisible: false,
            lyricsDrawerBottomVisible: false, // 底部弹出歌词层
        };
        this.getSong = this.getSong.bind(this);
        this.fitterShowPic = this.fitterShowPic.bind(this);
        this.OppenOhter = this.OppenOhter.bind(this);
        this.handleLyric = this.handleLyric.bind(this);
        this.getLyricInstance = this.getLyricInstance.bind(this);
        this.ClosedChangeVolume = this.ClosedChangeVolume.bind(this);
        this.OpenChangeVolume = this.OpenChangeVolume.bind(this);
        this.onDrawerClose = this.onDrawerClose.bind(this);
        this.onDrawerShow = this.onDrawerShow.bind(this);
        this.onEnd = this.onEnd.bind(this);
        this.ChangePlayType = this.ChangePlayType.bind(this);
        this.playDown = this.playDown.bind(this);
        this.playUp = this.playUp.bind(this);
        this.onCanPlay = this.onCanPlay.bind(this);
        this.OpenBottomDrawer = this.OpenBottomDrawer.bind(this);
        this.getSongLyrics = this.getSongLyrics.bind(this);

    }

    componentDidMount() {
        this.props.setLastAudioActive([]);
        this.eventEmitter = emitter.addListener('PlayAudio', (id,item) => {
            this.getSong(id,item,true);
        });
        this.CloseScreenLyrics = emitter.addListener('CloseScreenLyrics',() => {
            this.setState({
                lyricsDrawerBottomVisible: false,
            })
        })
        const { src, id, MusicInfo } = this.state;
        if(src === ''){
            this.setState({
                id: this.props.state.historyListActive,
                MusicInfo: this.props.state.historyActiveItem,
            });
            this.getSong(this.props.state.historyListActive,MusicInfo,false);
        }
    }

    getSong(id,item,isSend){
        // 获取到传递来的songid
        // console.log(id);
        if(lyricInstance){
            lyricInstance.stop();
        }
        lyricInstance = null;
        let params = {
            id,
        }
        GetSongUrls(params).then(res => {
            console.log(res);
            const { code, data } = res;
            if(code == 200){
                console.log(data[0].url);
                this.setState({
                    src: data[0].url,
                    id: data[0].id,
                    isSend: isSend,
                })
            }else {

            }
        }).catch(() => {

        })
        let detaildata = {
            ids: id,
        }
        GetAudioDetail(detaildata).then(res => {
            const { code, songs } = res;
            if(code == 200){
                this.setState({
                    MusicInfo: songs[0],
                });
                this.props.setHistoryActiveItem(songs[0]);
            }else {

            }
        }).catch(() => {

        })

        this.getSongLyrics(id);
    }

    getSongLyrics(id){
        let params = {
            id,
        }
        GetAudioLyric(params).then(res => {
            const { code, nolyric, lrc} = res;
            let lyric = "";
            if(code == 200){
                if(nolyric){
                    lyric = "[00:00.000] 暂无歌词";
                }else {
                    lyric = (lrc && lrc.lyric) || "[00:00.000] 纯音乐";
                }
            }else {
                lyric = "[00:00.000] 暂无歌词";
            }
            this.getLyricInstance(lyric);
        }).catch(() => {
            let lyric = "";
            lyric = "[00:00.000] 暂无歌词";
            this.getLyricInstance(lyric);
        })
    }

    getLyricInstance(lyric){
        lyricInstance = new Lyric(lyric, this.handleLyric)
        this.props.setLyricsList(lyricInstance);
    }

    handleLyric({ lineNum, txt }){
        const { isPlay, lyricsDrawerBottomVisible } = this.state
        if(isPlay){
            if(window.require){
                const { ipcRenderer } = window.require("electron");
                ipcRenderer.send('Changelyrics',txt);
            }
            this.props.setlyrics(txt);
            this.props.setLineLyrics(lineNum);
            if(lyricsDrawerBottomVisible){
                emitter.emit('ChangeLyrics');
            }
        }
    }


    componentWillUnmount(){
        emitter.removeListener(this.eventEmitter,function (){});
        emitter.removeListener(this.CloseScreenLyrics,function (){});
    }

    formatSecond(time) {
        const second = Math.floor(time % 60);
        let minite = Math.floor(time / 60);
        return `${minite}:${second >= 10 ? second : `0${second}`}`;
    }

    // 该视频已准备好开始播放
    onCanPlay = () => {
        const { id, isSend } = this.state;
        const audio = document.getElementById(`audio${id}`);
        this.setState({
            allTime: audio.duration,
            volume: audio.volume,
        });
        if(isSend){
            const { id, MusicInfo, allTime, lyricsDrawerBottomVisible } = this.state;
            const { historyList, lastActiveAudio } = this.props.state;
            let ishave = historyList.some(r => r.id === id);
            this.props.sethistoryactive(id);
            let newLastList = [...lastActiveAudio];
            if(!newLastList.some(r => r== id)){
                newLastList.push(id);
            }
            this.props.setLastAudioActive(newLastList);
            if(!ishave){
                let newlist = [...historyList];
                newlist.push({
                    id: id,
                    MusicInfo,
                    allTime: audio.duration,
                })
                this.props.sethistory(newlist);
            }

            this.setState({
                isPlay: true,
            })
            this.props.setIsAudioPlay(true);
            audio.play();
            // 播放下一首后告诉组件加载新的评论
            if(lyricsDrawerBottomVisible){
                this.ScreenRef.GetComment();
            }
            if(lyricInstance){
                lyricInstance.play();
            }
        }

    };

    onEnd(){
        this.playDown();
    }

    playAudio = () => {
        const { id, src } = this.state;
        const audio = document.getElementById(`audio${id}`);
        if(src){
            audio.play();
            if(lyricInstance){
                lyricInstance.stop();
                lyricInstance.play(audio.currentTime* 1000);

            }
            this.setState({
                isPlay: true,
            });
            this.props.setIsAudioPlay(true);
        }else {
            this.getSong(id,null,true);
        }

    };

    pauseAudio = () => {
        const { id } = this.state;
        const audio = document.getElementById(`audio${id}`);
        audio.pause();
        if(lyricInstance){
            lyricInstance.stop();
        }
        this.setState({
            isPlay: false,
        });
        this.props.setIsAudioPlay(false);

    };
    formatSeconds = (value) => {
        var theTime = parseInt(value);// 秒
        var middle= 0;// 分
        var hour= 0;// 小时

        if(theTime > 60) {
            middle= parseInt(theTime/60);
            theTime = parseInt(theTime%60);
            if(middle> 60) {
                hour= parseInt(middle/60);
                middle= parseInt(middle%60);
            }
        }
        let Time = parseInt(theTime).toString().padStart(2, '0')
        let Middle = parseInt(middle).toString().padStart(2, '0')
        let Hour = parseInt(theTime).toString().padStart(2, '0')
        var result = "00:"+Time;
        if(middle > 0) {
            result = Middle+":"+Time;
        }
        if(hour> 0) {
            result = Hour + ":" + Middle+":"+Time;
        }
        return result;
    }

    onMuteAudio = () => {
        const { id } = this.state;
        const audio = document.getElementById(`audio${id}`);
        this.setState({
            isMuted: !audio.muted,
        });
        audio.muted = !audio.muted;
    };

    changeTime = (value) => {
        this.setState({
            currentTime: value,
        });
        const { id } = this.state;
        const audio = document.getElementById(`audio${id}`);
        audio.currentTime = value;
        if (value === audio.duration) {
            this.setState({
                isPlay: false,
            });
            this.props.setIsAudioPlay(false);
        }
    };

    // 当前播放位置改变时执行
    onTimeUpdate = () => {

        const { id } = this.state;
        const audio = document.getElementById(`audio${id}`);

        this.setState({
            currentTime: audio.currentTime,
        });
        // console.log(lyricInstance);
        if(lyricInstance){
            lyricInstance.stop();
            lyricInstance.seek(audio.currentTime* 1000);
        }


        if (audio.currentTime === audio.duration) {
            this.setState({
                isPlay: false,
            });
            this.props.setIsAudioPlay(false);
        }
    };

    changeVolume = (value) => {
        const { id } = this.state;
        const audio = document.getElementById(`audio${id}`);
        audio.volume = value /100;
        this.setState({
            volume: value,
        });
    };


    // 倍速播放
    changePlayRate = (num) => {
        this.audioDom.playbackRate = num;
        this.setState({
            playRate: num,
        });
    };

    OpenBottomDrawer(){
        this.setState({
            lyricsDrawerBottomVisible: !this.state.lyricsDrawerBottomVisible,
        })
    }

    // 歌曲音乐头像显示
    fitterShowPic(){
        const { MusicInfo } = this.state;
        if (MusicInfo){
            let artistslist = [];
            MusicInfo.ar.map((item,key) => {
                artistslist.push(
                    <span key={key} artistid={item.id} className="Artists-Name">{item.name}</span>
                )
            })
            return <div className="Play_left">
                <div onClick={this.OpenBottomDrawer}>
                    <Avatar shape="square" size={50} src={MusicInfo?MusicInfo.al.picUrl:''}></Avatar>
                </div>
                <div className="Item-Text">
                    <div className="Text-Top">
                        <span className="Name">{MusicInfo.name}<span className="bie"></span></span>
                    </div>
                    <div className="Text-artists">
                        {artistslist}
                    </div>
                </div>
            </div>
        }else {
            return <div className="Play_left">
                <Avatar shape="square" size={50}></Avatar>
            </div>
        }
    }

    OppenOhter(){
        // 打开一个新的桌面显示词
        const { ipcRenderer } = window.require("electron");
        const { isopenlyrics, id } = this.state;

        if(isopenlyrics){
            ipcRenderer.send('lyricsClose');
            this.setState({
                isopenlyrics: false,
            })
        }else {
            ipcRenderer.send('oppenlyrics',id);
            this.setState({
                isopenlyrics: true,
            })
        }


    }


    OpenChangeVolume(){
        this.setState({
            showVolumeChange: true,
        })
    }

    ClosedChangeVolume(){
        this.setState({
            showVolumeChange: false,
        })
    }

    onDrawerClose(){
        this.setState({
            Drawervisible: false,
        })
    }

    onDrawerShow(){
        this.setState({
            Drawervisible: true,
        });
    }

    fitterPlayType(){
        const { PlayAudioType } = this.props.state;
        // 0 表示 顺序播放  1 - 随机播放 2 - 单曲循环 3 - 心动模式 4-列表循环
        switch (PlayAudioType){
            case 0:
                return 'icon-shunxubofang';
            case 1:
                return 'icon-suijibofang';
            case 2:
                return 'icon-danquxunhuan';
            case 3:
                return 'icon-xindong';
            case 4:
                return 'icon-liebiaoxunhuan';
            default:
                return 'icon-shunxubofang';
        }
    }

    ChangePlayType(){
        const { PlayAudioType } = this.props.state;
        let num = 0;
        if(PlayAudioType === 4){
            num = 0;
        }else {
            num = PlayAudioType + 1;
        }
        if(!getToken()){
            if(num === 3){
                num = 4;
            }
        }
        this.props.setPlayType(num);
    }

    playUp(){
        const { lastActiveAudio, historyListActive } = this.props.state;
        if(lastActiveAudio.length > 0){
            let index = lastActiveAudio.indexOf(lastActiveAudio.filter(r => r == historyListActive)[0]);
            if(index > 0){
                this.getSong(lastActiveAudio[index-1],null,true);
            }else {
                this.playDown();
            }
        }else {
            this.playDown();
        }
    }

    playDown(){
        const { historyList, PlayAudioType } = this.props.state;
        const { id } = this.state;
        // 0 表示 顺序播放  1 - 随机播放 2 - 单曲循环 3 - 心动模式 4- 列表循环
        let index = historyList.indexOf(historyList.filter(r => r.id == id)[0]);
        if(PlayAudioType === 0){
            // 顺序播放
            if(historyList.length - 1 > index){
                let id = historyList[index + 1].id;
                let item = historyList[index + 1].MusicInfo;
                this.getSong(id,item,true);
            }
        }else if(PlayAudioType === 1){
            // 随机播放
            let historyItem = historyList[Math.floor(Math.random()*historyList.length)];
            let id = historyItem.id;
            let item = historyItem.MusicInfo;
            this.getSong(id,item,true);
        }else if(PlayAudioType === 2){
            // 单曲循环
            const audio = document.getElementById(`audio${id}`);
            audio.duration = 0;
            this.setState({
                isPlay: true,
            })
            this.props.setIsAudioPlay(true);
            audio.play();
            if(lyricInstance){
                lyricInstance.play();
            }
        }else if(PlayAudioType === 3){
            // 心动模式
        }else if(PlayAudioType === 4){
            // 列表循环
            if(historyList.length - 1 > index){
                let id = historyList[index + 1].id;
                let item = historyList[index + 1].MusicInfo;
                this.getSong(id,item,true);

            }else if(index != 0){
                let id = historyList[0].id;
                let item = historyList[0].MusicInfo;
                this.getSong(id,item,true);
            }
        }

    }


    onRef = (ref) => {
        this.ScreenRef = ref;
    }



    render() {
        const { src, id } = this.state;
        const {
            isPlay,
            isMuted,
            volume,
            allTime,
            currentTime,
            rateList,
            playRate,
            MusicInfo,
            showVolumeChange,
            Drawervisible
        } = this.state;

        return (
            <div className={classnames('AudioPlay',{'fixedAudioPlay': this.state.lyricsDrawerBottomVisible})}>
                {/*放音乐图片*/}
                {this.fitterShowPic()}
                <div className="Play_center">
                    <audio
                        id={`audio${id}`}
                        src={src}
                        ref={(audio) => {
                            this.audioDom = audio;
                        }}
                        preload={"auto"}
                        onCanPlay={this.onCanPlay}
                        onTimeUpdate={this.onTimeUpdate}
                        onEnded={this.onEnd}
                    >
                        <track src={src} kind="captions" />
                    </audio>
                    <div className="AudioCZ">
                        <Button onClick={this.ChangePlayType} className="Audio_Button" icon={<i className={classnames('iconfont',this.fitterPlayType())}></i>}>

                        </Button>
                        <Button className="Audio_Button" type="text" onClick={this.playUp} shape="circle" icon={<i className="iconfont icon-shangyiqu"></i>} >

                        </Button>

                        <Button className="Audio_Button" type="text" onClick={isPlay?this.pauseAudio:this.playAudio} shape="circle" icon={<i className={isPlay?'iconfont icon-bofangzhong':'iconfont icon-zanting'} ></i>} >

                        </Button>

                        <Button className="Audio_Button" type="text" onClick={this.playDown} shape="circle" icon={<i className="iconfont icon-xiayiqu"></i>} >

                        </Button>

                        <Button className="Audio_Button" onClick={this.OppenOhter}>
                            词
                        </Button>

                    </div>
                    <div className="AudioLine">
                        <span>{this.formatSeconds(currentTime)}</span>
                        <Slider onChange={this.changeTime} className="Line" value={currentTime} min={0} step={0.01} max={parseFloat(allTime)} tipFormatter={null} />
                        <span>{this.formatSeconds(allTime)}</span>
                    </div>
                </div>
                <div className="Play_right">
                    {/*放列表等等*/}
                    <div onMouseLeave={this.ClosedChangeVolume} onMouseEnter={this.OpenChangeVolume} className="Audio_Volume">
                        <i className="iconfont icon-yinliang"></i>
                        {showVolumeChange? <Slider className="Volume_Line" onChange={this.changeVolume} defaultValue={volume} min={0} step={1} max={100} tipFormatter={null} />: ''}
                    </div>

                    <Button className="Audio_Button" onClick={this.onDrawerShow} type="text" icon={<i className="iconfont icon-bofangduilie"></i>} >

                    </Button>


                </div>
                <Drawer
                    zIndex={4000}
                    placement="right"
                    width={400}
                    closable={false}
                    visible={this.state.Drawervisible}
                    onClose={this.onDrawerClose}
                    maskStyle={{backgroundColor:'transparent'}}
                    getContainer={() => {
                        return document.getElementById('App_Content');
                    }}
                    style={{ position: 'absolute' }}
                >
                    <MusicHistoryList />
                </Drawer>

                {/*这个是底部弹窗*/}

                <Drawer
                    className="lyricsBottom_Box"
                    placement="bottom"
                    closable={false}
                    visible={this.state.lyricsDrawerBottomVisible}
                    getContainer={() => {
                        return document.getElementById('root');
                    }}
                    mask={false}
                    // destroyOnClose={true}
                    height="100%"
                    // style={{height: "100%"}}
                >
                    <ScreenLyricsPage onRef={this.onRef} />
                </Drawer>

            </div>
        );
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(AudioPlay);